<?php 
header("content-type:text/html;charset=utf8");
//接id
$g_id=$_GET["id"];
// print_r($g_id);die;
//开启缓存
$redis=new redis();
//连接
$redis->connect("127.0.0.1","6379");
//连选库
$db=new PDO("mysql:host=127.0.0.1;dbname=bj07c;charset=utf8","root","root");
$sql="select * from goods_qg where g_id=$g_id";
$res=$db->query($sql)->fetch(PDO::FETCH_ASSOC);
$g_stock=$res["g_stock"];
//把数据库存放在redis中防止高并发
for ($i=1; $i<=$g_stock ; $i++) { 
	 $redis->lpush("xg".$g_id,$i);
}
// print_r($g_stock);die;
$starttime=time();
$endtime=strtotime($res["endtime"]);
// print_r($endtime);
if($starttime>$endtime)
{
  echo "<script>alert('时间已经过期,请下次再来');location.href='show.php';</script>";
}
else
{
  if($g_stock<=0)
  {
    echo "<script>alert('很遗憾,抢光了');location.href='show.php';</script>";
  }
  else
  {
      if($redis->lrange("xg".$g_id))
      {
         $redis->rpop("xg".$g_id);
         $sql="update goods_qg set g_stock=$g_stock-1 where g_id=$g_id";
	     $res=$db->exec($sql);
	      if($res)
		  {
		  	echo "<script>alert('抢购成功');location.href='dd.php';</script>";
		  }
      }
      else
	  {
		  echo "<script>alert('抢购失败');location.href='show.php';</script>";
		 }

  }

}
 ?>

